package pl.matt.media.extractor;

import java.awt.Image;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import pl.matt.io.utils.FileUtils;
import pl.matt.media.utils.ImageUtils;

/**
 * @author mateusz
 * 
 */
public class NoseExtractor {

	private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(NoseExtractor.class);
	
	private String sourceDirectory = "resources/images/bioId/";
	private String destinationDirectory = "resources/images/noses";

	private String imageExtension = ".pgm";
	private String noseExtension = ".nose";

	private int noseHeight = 50;
	private int noseWidth = 50;

	private void extract() {
		File directory = new File(sourceDirectory);
		String[] files = directory.list(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(noseExtension);
			}
		});
		for (int i = 0; i < files.length; i++) {
			try {
				String noseFileName = sourceDirectory + File.separator + files[i];
				String imgFileName = noseFileName.replaceFirst(noseExtension, imageExtension);
				String line = FileUtils.readLineFromFile(noseFileName, 2);
				line = line.replaceAll(" +", "\t");
				//System.out.println("--" + line + "--");
				String[] digits = line.split("\t");
				int x = Integer.valueOf(digits[0]);
				int y = Integer.valueOf(digits[1]);

				Image srcImage = ImageUtils.readImage(imgFileName).getAsBufferedImage();
				Image eye = ImageUtils.cropImage(srcImage, x - noseWidth / 2, y - noseHeight / 2, noseWidth, noseHeight);
				
				String dstFileName = destinationDirectory + File.separator + files[i].replaceFirst(noseExtension, ".jpeg");
				
				ImageUtils.writeImage(eye, dstFileName);
				LOG.debug(dstFileName + " <-- dstFileName saved");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public static void main(String[] args) {
		NoseExtractor extractor = new NoseExtractor();
		extractor.extract();
	}

}
